package com.hnkywl.sts.service.kcgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.cggl.GlfyDao;
import com.hnkywl.sts.dao.cggl.GlfymxDao;
import com.hnkywl.sts.dao.kcgl.CkshDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.dao.xsgl.XsdDao;
import com.hnkywl.sts.entity.cggl.Cgd;
import com.hnkywl.sts.entity.cggl.Cgdmx;
import com.hnkywl.sts.entity.cggl.Glfy;
import com.hnkywl.sts.entity.cggl.Glfymx;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.entity.xsgl.Xsd;
import com.hnkywl.sts.entity.xsgl.Xsmx;
import com.hnkywl.sts.service.cggl.CgdService;
import com.hnkywl.sts.service.sys.YgService;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-5-3
 * Time: 上午11:00
 * To change this template use File | Settings | File Templates.
 */
@Service
public class CkshService {
    private CgdService cgdService;
    private CkshDao ckshDao;
    private Xsd xsd;
    private Kh kh;
    private KhDao khDao;
    private XsdDao xsdDao;
    private CgdDao cgdDao;
    private GlfyDao glfyDao;
    private GlfymxDao glfymxDao;

    @Transactional
    public String findAllCksh(String wzbm, String xsdh, Long khId, Long ckId, Date zdrqStart, Date zdrqEnd, Long xsgsId, String yck, String yps, int pageNo, int pageSize, Date cksjStart, Date cksjEnd) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        java.text.DecimalFormat df = new java.text.DecimalFormat("0.0000");
        Page ckshPage = this.ckshDao.findAllCkshList(wzbm, xsdh, khId, ckId, zdrqStart, zdrqEnd, xsgsId, new String[]{"kcls", "htxs", "bgxs", "nbxs"}, new String[]{"ytj", "ysp"}, yck, yps, pageNo, pageSize, cksjStart, cksjEnd);
        String ckshJson = gson.toJson(ckshPage.getResult());
        List<Map> list = this.ckshDao.findSumCkshList(wzbm, xsdh, khId, ckId, zdrqStart, zdrqEnd, xsgsId, new String[]{"kcls", "htxs", "bgxs", "nbxs"}, new String[]{"ytj", "ysp"}, yck, yps, cksjStart, cksjEnd);
        if (list.size() > 0) {
            Double kdsl = 0d;
            Double sl = 0d;
            for (Map map : list) {
                kdsl += map.get("ck_sbsl") == null ? 0d : Double.parseDouble(map.get("ck_sbsl").toString());
                sl += map.get("xssl") == null ? 0d : Double.parseDouble(map.get("xssl").toString());
            }
            return "{\"total\":" + ckshPage.getTotalCount() + ",\"rows\":" + ckshJson + ",\"footer\":[{\"xsdh\":\"合计:\",\"xssl\":" + df.format(sl)
                    + ",\"ck_sbsl\":\"" + df.format(kdsl) + "\"}]}";
        } else {
            return "{\"total\":" + ckshPage.getTotalCount() + ",\"rows\":" + ckshJson + "}";
        }
    }

    public String findCkdList() {
        return this.ckshDao.findCkdList();
    }

    public String findAllSlsh(String wzbm, String xsdh, Long khId, Long ckId, Date zdrqStart, Date zdrqEnd, Long xsgsId, String yck, int pageNo, int pageSize) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page ckshPage = this.ckshDao.findAllSlslList(wzbm, xsdh, khId, ckId, zdrqStart, zdrqEnd, xsgsId, new String[]{"zddh"}, new String[]{"ytj", "ysp"}, yck, null, pageNo, pageSize);
        String ckshJson = gson.toJson(ckshPage.getResult());
        return "{\"total\":" + ckshPage.getTotalCount() + ",\"rows\":" + ckshJson + "}";
    }

    public Xsd findXsd(Long xsdId) {
        return this.ckshDao.get(xsdId);
    }

    /**
     * 审核销售明细
     *
     * @param xsd
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public synchronized void checkCksh(Xsd xsd) {
        if (this.xsdDao.get(xsd.getId()) != null && !this.xsdDao.get(xsd.getId()).getYck()) {
            List<Xsmx> xsmxList = xsd.getXsmxList();
            Xsd x = findXsd(xsd.getId());
            List<Xsmx> list = x.getXsmxList();
            for (int i = 0; i < xsmxList.size(); i++) {
                for (Xsmx xsmx : list) {
                    if (xsmx.getId().equals(xsmxList.get(i).getId())) {
                        xsmx.setCk_js(xsmxList.get(i).getCk_js() == null ? xsmxList.get(i).getJs() : xsmxList.get(i).getCk_js());
                        xsmx.setCk_sbsl(xsmxList.get(i).getCk_sbsl() == 0 ? xsmxList.get(i).getSbsl() : xsmxList.get(i).getCk_sbsl());
                        xsmx.setCkbhse(xsmxList.get(i).getBhsj() * xsmxList.get(i).getCk_sbsl());
                        break;
                    }
                }
            }
            if (!x.getYck()) {
                Map<Long, Double> khSl = new HashMap<Long, Double>();
                for (Xsmx xsmx : list) {
                    if (xsmx.getKh() != null) {
                        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
                        Double value = khSl.get(xsmx.getKh().getId());
                        String sbslstr = df.format(xsmx.getCk_sbsl());
                        if (value != null) {
                            String valuestr = df.format(value);
                            value = Double.parseDouble(valuestr);
                            khSl.put(xsmx.getKh().getId(), value + Double.parseDouble(sbslstr));
                        } else {
                            khSl.put(xsmx.getKh().getId(), Double.parseDouble(sbslstr));
                        }
                    }
                }

                for (Long id : khSl.keySet()) {
                    Kh kh = this.khDao.get(id);
                    if (kh.getSl() - khSl.get(id) < 0)
                        throw new RuntimeException("出库数量大于库存数量，无法提交！");
                }

                for (Xsmx xsmx : list) {
                    if (xsmx.getKh() != null) {
                        Kh kh = khDao.findUniqueByProperty("id", xsmx.getKh().getId());
                        if (kh != null) {
                            java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
                            String slstr = df.format(kh.getSl() - xsmx.getCk_sbsl());
                            String kkdslstr = df.format(kh.getKkdsl() - xsmx.getCk_sbsl());
                            Double sl = Double.parseDouble(slstr);
                            Double kkdsl = Double.parseDouble(kkdslstr);
                            kh.setSl(sl);
                            kh.setCkrq(new Date());
                            kh.setJs((kh.getJs() == null ? 0 : kh.getJs()) - (xsmx.getCk_js() == null ? 0 : xsmx.getCk_js()));
                            kh.setKkdsl(kkdsl);
                            khDao.save(kh);
                        }
                    }
                }
            }

            x.setCkshbz(true);
            try {
                x.setCkr(YgService.getCurrentYg());
            } catch (Exception e) {

            }
            x.setZt("ysp");
            x.setCwsh(true);
            x.setYck(true);
            x.setLastUpdated(new Date());
            x.setCksj(new Date());
            this.ckshDao.save(x);
        } else {
            Xsd x = findXsd(xsd.getId());
            x.setZt("ysp");
            this.ckshDao.save(x);
        }
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    private void saveKhs(List<Xsmx> xsmxes) {
        for (Xsmx xsmx : xsmxes) {
            Kh kh = khDao.findUniqueByProperty("id", xsmx.getKh().getId());
            java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
            String slstr = df.format(kh.getSl() - xsmx.getCk_sbsl());
            String kkdslstr = df.format(kh.getKkdsl() + xsmx.getSbsl() - xsmx.getCk_sbsl());
            Double sl = Double.parseDouble(slstr);
            Double kkdsl = Double.parseDouble(kkdslstr);
            kh.setSl(sl);
            kh.setKkdsl(kkdsl);
            khDao.save(kh);
        }
    }

    @Transactional
    public void slsh(Long xsdId) {
        Xsd xsd = xsdDao.get(xsdId);
        xsd.setYck(true);
        xsd.setCksj(new Date());
        //xsd.setXsr(YgService.getCurrentYg());
        xsd.setCkr(YgService.getCurrentYg());
        xsd.setZt("ysp");
        if (xsd.getXsmxList() != null) {
            for (int i = 0; i < xsd.getXsmxList().size(); i++) {
                xsd.getXsmxList().get(i).setCk_sbsl(xsd.getXsmxList().get(i).getSbsl());
            }
        }
        xsdDao.save(xsd);
        Cgd cgd = this.cgdDao.findUniqueByProperty("xsd.id", xsdId);
        if (cgd != null) {
            cgd.setZt("ysp");
            cgd.setYrk(true);
            cgd.setRkr(YgService.getCurrentYg());
            cgd.setRksj(new Date());
            List<Cgdmx> cgdmxes = new ArrayList<Cgdmx>();
            if (cgd.getCgdmxList() != null) {
                cgdmxes = cgd.getCgdmxList();
                for (int i = 0; i < cgd.getCgdmxList().size(); i++) {
                    cgd.getCgdmxList().get(i).setRksl(cgd.getCgdmxList().get(i).getSbsl());
                }
            }
            cgdDao.save(cgd);
            if (cgd.getCgfyList() != null) {
                List<Glfy> glfyList = cgd.getCgfyList();
                java.text.DecimalFormat df2 = new java.text.DecimalFormat("#0.00");
                Double sumSl = sumSl(cgdmxes);
                Double sumJtfy = 0d;
                for (Glfy glfy : glfyList) {
                    for (int i = 0; i < cgdmxes.size(); i++) {
                        if (i < cgdmxes.size() - 1) {
                            Glfymx glfymx = new Glfymx();
                            glfymx.setGg(cgdmxes.get(i).getGg());
                            glfymx.setCgdmx(cgdmxes.get(i));
                            glfymx.setGlfy(glfy);
                            glfymx.setJtfy(Double.valueOf(df2.format(glfy.getJe() / sumSl * cgdmxes.get(i).getRksl())));
                            glfymx.setDateCreated(new Date());
                            glfymx.setLastUpdated(glfymx.getDateCreated());
                            glfymx.setCreateUser(YgService.getCurrentYg());
                            glfymx.setCreateOrgan(YgService.getCurrentYg().getZggs());
                            glfymx.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                            glfymxDao.save(glfymx);
                            sumJtfy += Double.valueOf(df2.format(glfymx.getJtfy()));
                        } else if (i == cgdmxes.size() - 1) {
                            Glfymx glfymx = new Glfymx();
                            glfymx.setGg(cgdmxes.get(i).getGg());
                            glfymx.setCgdmx(cgdmxes.get(i));
                            glfymx.setGlfy(glfy);
                            glfymx.setJtfy(Double.valueOf(df2.format(glfy.getJe() - sumJtfy)));
                            glfymx.setDateCreated(new Date());
                            glfymx.setLastUpdated(glfymx.getDateCreated());
                            glfymx.setCreateUser(YgService.getCurrentYg());
                            glfymx.setCreateOrgan(YgService.getCurrentYg().getZggs());
                            glfymx.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                            glfymxDao.save(glfymx);
                        }
                    }
                    sumJtfy = 0d;
                    glfy.setLastUpdated(new Date());
                    glfyDao.save(glfy);
                }
            }
        }

        this.cgdService.createZddhdj(cgd);
    }

    //统计采购单明细省报数量
    private Double sumSl(List<Cgdmx> cgdmxList) {
        Double sumSl = 0d;
        for (Cgdmx cgdmx : cgdmxList) {
            sumSl += cgdmx.getRksl() == null ? 0 : cgdmx.getRksl();
        }
        return sumSl;
    }

    public String findCkshmxDetail(Long xsdId) {
        Gson gson = new Gson();
        List<Map> xsdmxList = this.ckshDao.findCkshList(xsdId);
        String json = gson.toJson(xsdmxList);
        return "{\"rows\":" + json + "}";
    }

    public String findZddhmxDetail(Long xsdId) {
        Gson gson = new Gson();
        List<Map> xsdmxList = this.ckshDao.findZddhXsmxList(xsdId);
        String json = gson.toJson(xsdmxList);
        return "{\"rows\":" + json + "}";
    }

    public Xsd getXsd() {
        return xsd;
    }

    public void setXsd(Xsd xsd) {
        this.xsd = xsd;
    }

    public Kh getKh() {
        return kh;
    }

    public void setKh(Kh kh) {
        this.kh = kh;
    }

    @Autowired
    public void setCkshDao(CkshDao ckshDao) {
        this.ckshDao = ckshDao;
    }

    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }

    @Autowired
    public void setXsdDao(XsdDao xsdDao) {
        this.xsdDao = xsdDao;
    }

    @Autowired
    public void setCgdDao(CgdDao cgdDao) {
        this.cgdDao = cgdDao;
    }

    @Autowired
    public void setCgdService(CgdService cgdService) {
        this.cgdService = cgdService;
    }

    @Autowired
    public void setGlfyDao(GlfyDao glfyDao) {
        this.glfyDao = glfyDao;
    }

    @Autowired
    public void setGlfymxDao(GlfymxDao glfymxDao) {
        this.glfymxDao = glfymxDao;
    }
}
